#include "rgb2cmyk.h"
#include <stdio.h>
#include <assert.h>
#include <string.h>

int main() {
    RGB rgb_image[HEIGHT][WIDTH];
    CMYK cmyk_image[HEIGHT][WIDTH];

    int has_errors = 0;
    char data_buf[256];
    char check_buf[256];

    for (int i = 0; i < HEIGHT; i++) {
        for (int j = 0; j < WIDTH; j++) {
            rgb_image[i][j].r = (i + j) % 256;
            rgb_image[i][j].g = (256 - j) % 256;
            rgb_image[i][j].b = (2 * i) % 256;
        }
    }

    rgb_to_cmyk(rgb_image, cmyk_image);

    FILE *fp = fopen("check.data", "r");
    assert(fp != NULL && "Couldn't open check data file");

    for (int i = 0; i < HEIGHT; i++) {
        for (int j = 0; j < WIDTH; j++) {
            CMYK c = cmyk_image[i][j];

            sprintf(data_buf, "%0.4f", c.c);
            int res = fscanf(fp, "%s", check_buf);
            assert(res == 1 && "read check data file failed");
            if (strcmp(data_buf, check_buf)) {
                printf("c[%d][%d] = %s, expected_c[%d][%d] = %s\n",
                       i, j,
                       data_buf,
                       i, j,
                       check_buf);
                has_errors++;
            }

            sprintf(data_buf, "%0.4f", c.m);
            res = fscanf(fp, "%s", check_buf);
            assert(res == 1 && "read check data file failed");
            if (strcmp(data_buf, check_buf)) {
                printf("m[%d][%d] = %s, expected_m[%d][%d] = %s\n",
                       i, j,
                       data_buf,
                       i, j,
                       check_buf);
                has_errors++;
            }

            sprintf(data_buf, "%0.4f", c.y);
            res = fscanf(fp, "%s", check_buf);
            assert(res == 1 && "read check data file failed");
            if (strcmp(data_buf, check_buf)) {
                printf("y[%d][%d] = %s, expected_y[%d][%d] = %s\n",
                       i, j,
                       data_buf,
                       i, j,
                       check_buf);
                has_errors++;
            }

            sprintf(data_buf, "%0.4f", c.k);
            res = fscanf(fp, "%s", check_buf);
            assert(res == 1 && "read check data file failed");
            if (strcmp(data_buf, check_buf)) {
                printf("k[%d][%d] = %s, expected_k[%d][%d] = %s\n",
                       i, j,
                       data_buf,
                       i, j,
                       check_buf);
                has_errors++;
            }
        }
    }

    fclose(fp);

    if (has_errors) {
        fprintf(stderr, "Benchmark results are incorrect\n");
        return -1;
    }

    printf("Success.\n");
    return 0;
}
